package org.hugh.space.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hugh.space.business.BackService;
import org.hugh.space.business.FrontService;
import org.jabsorb.JSONRPCBridge;

public class ServiceFilter extends AbstractFilter implements Filter {

	public ServiceFilter() {
		super();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(true);
        boolean backService = isLoggedIn(httpRequest);
		enableFrontService(session);
        if (backService) {
        	enableBackService(session);
        }
        chain.doFilter(request, response);
		disableFrontService(session);
        if (backService) {
			disableBackService(session);
		}
	}

	private void enableBackService(HttpSession session) {
		JSONRPCBridge bridge = getJSONRPCBridge(session);
		getBackService().register(bridge);
	}

	private void enableFrontService(HttpSession session) {
		JSONRPCBridge bridge = getJSONRPCBridge(session);
		getFrontService().register(bridge);
	}
	
	private void disableBackService(HttpSession session) {
		JSONRPCBridge bridge = getJSONRPCBridge(session);
		getBackService().unregister(bridge);
	}

	private void disableFrontService(HttpSession session) {
		JSONRPCBridge bridge = getJSONRPCBridge(session);
		getFrontService().unregister(bridge);
	}

	private JSONRPCBridge getJSONRPCBridge(HttpSession session) {
		if (session.getAttribute("JSONRPCBridge") == null) {
			session.setAttribute("JSONRPCBridge", new JSONRPCBridge());
		}
		return (JSONRPCBridge) session.getAttribute("JSONRPCBridge");
	}

	private boolean isLoggedIn(final HttpServletRequest request) {
//		return getBusiness().getUserPreferences(request).isLoggedIn();
		return false;
	}

	private FrontService getFrontService() {
		return (FrontService)getSpringBean("frontService");
	}

	private BackService getBackService() {
		return (BackService)getSpringBean("backService");
	}
	
}